package com.fm.service;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.Socket;
import java.util.Scanner;

import static com.fm.service.service.TCPClient;

public class service_download {

    /**
     * 下载
     */
    public static void download(String num){
        //发送选项标识,建立连接
        Socket socket = TCPClient(num);

        // 从键盘获取下载序号
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要下载的文件序号: ");
        String SerialNumber = scanner.nextLine();

        try{
            //传输序号
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeInt(Integer.parseInt((SerialNumber)));

            socket.shutdownOutput();

            //文件名
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            int len = dataInputStream.readInt();
            byte[] fileName = new byte[1024];
            socket.getInputStream().read(fileName,0,len);

            //文件数据
            int Datalen;
            FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/DownLoad/"+new String(fileName,0,len));
            byte[] bytes = new byte[1024];
            while ((Datalen = (socket.getInputStream().read(bytes)))!=-1) {
                fileOutputStream.write(bytes,0,Datalen);
            }

            System.out.println(new String(fileName,0,len)+"  下载成功!");

            //关闭
            socket.close();

        }catch (Exception e){
            e.printStackTrace();
        }


    }


}
